﻿using System;
using System.IO;
using BookiFramework.Abstracts;

namespace BookiFramework.Files
{
    public class FileWritter
    {
        public OperationResult WriteText(string filename,string text, bool overwrite = false)
        {
            if(!File.Exists(filename)) return OperationResult.Fail("The file no exist.");

            using (var stream = new FileStream(filename,overwrite? FileMode.Truncate:FileMode.Open, FileAccess.ReadWrite))
            {
                new Files().WriteText(stream,text,!overwrite,true);
            }
            return OperationResult.Correct();
        }

        public OperationResult EmptyFile(string filename)
        {
            if (!File.Exists(filename)) return OperationResult.Fail("The file no exist.");

            using (var stream = new FileStream(filename, FileMode.Truncate))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(String.Empty);
                }
            }

            return OperationResult.Correct();
        }

        public OperationResult WriteTextNewFile(string filename, string text, bool overwriteIfExist)
        {
            if(File.Exists(filename) && !overwriteIfExist) return OperationResult.Fail("The file exist.");

            using (var stream = new FileStream(filename, overwriteIfExist?FileMode.OpenOrCreate : FileMode.CreateNew))
            {
                stream.SetLength(0);
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(String.Empty);
                }
            }
            return OperationResult.Correct();
        }
    }
}
